# -*- coding:utf-8 -*-
"""
@Time : 2020/3/31 16:31
@Author : SongBin
@File : ComplexEncoder.py
@remarks: 
"""
import json
from datetime import date, datetime
from decimal import Decimal
import  demjson
from sqlalchemy.ext.declarative import DeclarativeMeta

from framework.vo.ViewObject import ViewObject


class ComplexEncoder(json.JSONEncoder):
    def default(self, obj):
        # sl加对model对象的转换
        if isinstance(obj.__class__, DeclarativeMeta):

            fields = {}
            for field in [x for x in dir(obj) if
                          not x.startswith('_') and x != 'metadata' and x != 'query' and x != 'query_class']:
                data = obj.__getattribute__(field)
                try:
                    if data == None:
                        fields[field] = ''
                    elif isinstance(data, ViewObject):
                        # json.dumps(data,cls=ComplexEncoder)
                        fields[field] = json.dumps(data, ensure_ascii=False, cls=ComplexEncoder)
                        # fields[field] =json.dumps(data, default=lambda obj: obj.__dict__)
                    else:
                        fields[field] = data

                except TypeError:
                    fields[field] = data
            return fields
        # sl加对普通对象的转换
        elif isinstance(obj, ViewObject):
            return demjson.decode(json.dumps(obj, ensure_ascii=False, default=lambda obj1: obj1.__dict__))
        elif isinstance(obj, datetime):
            return obj.strftime('%Y-%m-%d %H:%M:%S')
        elif isinstance(obj, date):
            return obj.strftime('%Y-%m-%d')
        elif isinstance(obj, Decimal):
            return str(obj)
        else:
            return json.JSONEncoder.default(self, obj)
